package hikari.gui.guicomponents;

import com.gooddies.events.ValueChangedEvent;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.BorderFactory;
import javax.swing.JColorChooser;
import javax.swing.JPanel;
import org.swig.jirr.SColor;

/**
 * @author sad
 */
public class ColorPicker extends JPanel {
    public static interface ColorChangedEvent {
        void colorChaged(Color color);
    };
    private ValueChangedEvent<Color> event;

    public ColorPicker() {
        setPreferredSize(new Dimension(20, 20));
        setBorder(BorderFactory.createLineBorder(Color.BLACK));
        setBackground(Color.WHITE);
        setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                Color color = JColorChooser.showDialog(ColorPicker.this, "Please select color", getSelectedColor());
                if (color == null) {
                    return;
                }
                setSelectedColor(color);
                if (event != null) {
                    event.fire(color, ColorPicker.this);
                }
                
            }
        });
    }

    @Override
    public void paint(Graphics g) {
        if (isEnabled() == false) {
            g.setColor(Color.lightGray);
            g.fillRect(0, 0, getWidth(), getHeight());
        } else {
            super.paint(g);
        }
    }

    @Override
    public void setEnabled(boolean enabled) {
        super.setEnabled(enabled);
        repaint();
    }

    public void setValueChangedEvent(ValueChangedEvent<Color> event) {
        this.event = event;
    }

    public void setSelectedColor(Color color) {
        setBackground(color);
    }

    public void setSelectedColor(SColor color) {
        setSelectedColor(color.getJavaColor());
    }

    public Color getSelectedColor() {
        return getBackground();
    }
}
